from support.utils.toolkit import Log
from support.sys.dispatch import Dispatch
from SimpleWebSocketServer import SimpleWebSocketServer, WebSocket

class ShellServer(SimpleWebSocketServer):            
    def broadcast(self, msg):
        for client in self.clients():
            client.sendMessage(msg)
    
    def addClient(self, client):
        self.clients.append(client)
    
    def removeClient(self, client):
        self.clients.remove(client)
        
    def init(self):
        self.clients = []
    
    def run(port):
        server =  ShellServer('', port, RecvHandler)
        server.init()
        Log.i("Shell Server is running on {}".format(port))
        server.serveforever()
        
class RecvHandler(WebSocket):
    def handleMessage(self):
        response = Dispatch.onRequest(self.data)
        if(isinstance(response,tuple)):
            for data in response:
                self.sendMessage(data)
        else:
            self.sendMessage(response)
    
    def handleConnected(self):
        Log.d("connected")
        self.server.addClient(self)
    
    def handleClose(self):
        Log.d("close")
        self.server.removeClient(self)
